import React from 'react';
import {
  Box,
  Container,
  Paper,
  Typography,
  TextField,
  Button,
  Link,
  FormControlLabel,
  Checkbox,
  Alert,
  useTheme
} from '@mui/material';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useNavigate, Link as RouterLink } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { useLoginMutation } from '../../store/services/auth';
import { setCredentials } from '../../store/slices/authSlice';
import Loading from '../../components/common/Loading';

interface LoginForm {
  username: string;
  password: string;
  remember: boolean;
}

const Login: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const theme = useTheme();
  const [login, { isLoading, error }] = useLoginMutation();

  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm<LoginForm>({
    defaultValues: {
      username: '',
      password: '',
      remember: false
    }
  });

  const onSubmit = async (data: LoginForm) => {
    try {
      const result = await login({
        username: data.username,
        password: data.password
      }).unwrap();

      dispatch(setCredentials(result.data));

      if (data.remember) {
        // 如果选择了"记住我"，可以在这里存储一些持久化的登录信息
        localStorage.setItem('rememberMe', 'true');
      }

      navigate('/');
    } catch (err) {
      // 错误已经由 RTK Query 处理
      console.error('Login failed:', err);
    }
  };

  if (isLoading) {
    return <Loading />;
  }

  return (
    <Container component="main" maxWidth="xs">
      <Box
        sx={{
          marginTop: 8,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
        }}
      >
        <Paper
          elevation={3}
          sx={{
            p: 4,
            width: '100%',
            borderRadius: 2,
            bgcolor: 'background.paper'
          }}
        >
          <Typography component="h1" variant="h5" align="center" gutterBottom>
            {t('auth.login.title')}
          </Typography>

          {error && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {t('auth.login.error')}
            </Alert>
          )}

          <Box component="form" onSubmit={handleSubmit(onSubmit)} sx={{ mt: 1 }}>
            <TextField
              margin="normal"
              required
              fullWidth
              id="username"
              label={t('auth.login.username')}
              autoComplete="username"
              autoFocus
              error={!!errors.username}
              helperText={errors.username?.message}
              {...register('username', {
                required: t('auth.login.usernameRequired'),
                minLength: {
                  value: 3,
                  message: t('auth.login.usernameMinLength')
                }
              })}
            />

            <TextField
              margin="normal"
              required
              fullWidth
              id="password"
              label={t('auth.login.password')}
              type="password"
              autoComplete="current-password"
              error={!!errors.password}
              helperText={errors.password?.message}
              {...register('password', {
                required: t('auth.login.passwordRequired'),
                minLength: {
                  value: 6,
                  message: t('auth.login.passwordMinLength')
                }
              })}
            />

            <FormControlLabel
              control={
                <Checkbox
                  color="primary"
                  {...register('remember')}
                />
              }
              label={t('auth.login.remember')}
            />

            <Button
              type="submit"
              fullWidth
              variant="contained"
              sx={{ mt: 3, mb: 2 }}
              disabled={isLoading}
            >
              {t('auth.login.submit')}
            </Button>

            <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
              <Link
                component={RouterLink}
                to="/forgot-password"
                variant="body2"
                color="primary"
              >
                {t('auth.login.forgot')}
              </Link>

              <Link
                component={RouterLink}
                to="/register"
                variant="body2"
                color="primary"
              >
                {t('auth.login.register')}
              </Link>
            </Box>
          </Box>
        </Paper>
      </Box>
    </Container>
  );
};

export default Login; 